package com.lebang.service.rouseday;

import com.lebang.component.RedisClient;
import com.lebang.domain.RouseCountConfig;
import com.lebang.domain.RouseCountMemberRecord;
import com.lebang.domain.RouseDayConfig;
import com.lebang.domain.RouseDayMemberRecord;
import com.lebang.entity.RequestHeaders;
import com.lebang.example.RouseCountConfigExample;
import com.lebang.example.RouseDayConfigExample;
import com.lebang.mapper.RouseCountConfigMapper;
import com.lebang.mapper.RouseCountMemberRecordMapper;
import com.lebang.mapper.RouseDayConfigMapper;
import com.lebang.mapper.RouseDayMemberRecordMapper;
import com.lebang.model.Whether;
import com.lebang.model.enums.buss.RewardTypeUscan;
import com.lebang.model.enums.buss.TaskCategory;
import com.lebang.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;

/**
 * rouse_day_config
 *
 * @Author hwq
 * @Date 2020-06-11
 */
@Service
public class RouseDayConfigService extends BaseService<RouseDayConfig, Integer, RouseDayConfigExample> {
    @Autowired
    private RouseDayMemberRecordMapper recordMapper;
    @Autowired
    private RouseDayConfigMapper baseMapper;
    public static final String COUNT_KEY = "RouseDayCount:";
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private RouseCountConfigMapper rouseCountConfigMapper;
    @Autowired
    private RouseCountMemberRecordMapper countRecordMapper;

    /**
     * 获取进度
     * @param headers
     * @return
     */
    public Integer getCount(RequestHeaders headers) {
        return Optional.ofNullable(redisClient.hget(getCountKey(),headers.getUserid()))
                .map(Integer::parseInt)
                .orElse(0);
    }
    /**
     * 获取每日任务的配置。
     *
     * @return
     */
    public List<RouseDayConfig> selectConfigList(RequestHeaders headers) {
        RouseDayConfigExample example = new RouseDayConfigExample();
        example.setOrderByClause("sort");
        example.createCriteria()
                .andEnableEqualTo(Whether.YES.getDbIndex())
                .andHasDeletedEqualTo(Whether.NO.getDbIndex())
        .andBrandNotLike("%" + headers.getAppStore() + "%");
        return this.selectByExample(example);
    }

    /**
     * 获取每日阀值的配置。
     *
     * @return
     */
    public List<RouseCountConfig> selectCountConfigList() {
        RouseCountConfigExample example = new RouseCountConfigExample();
        example.setOrderByClause("count asc");
        example.createCriteria().andEnableEqualTo(Whether.YES.getDbIndex()).andHasDeletedEqualTo(Whether.NO.getDbIndex());
        return rouseCountConfigMapper.selectByExample(example);
    }

    /**
     * 验证是否做过今天是每日阈值任务
     *
     * @param memberId
     * @param rouseConfigId
     * @return
     */
    public int checkConfigByMemberId(String memberId, Integer rouseConfigId) {
        LocalDate now = LocalDate.now();
        return Optional.ofNullable(recordMapper.selectByMemberIdAndConfigId(memberId, rouseConfigId, now)).orElse(0);
    }

    /**
     * 完成每日任务
     *
     * @param taskCategory 任务类型
     * @param count        第几次完成
     */
    @Async
    public void endRecord(TaskCategory taskCategory, int count, RequestHeaders requestHeaders) {
        LocalDate now = LocalDate.now();
        RouseDayConfig config = baseMapper.selectByCategory(taskCategory.name(), count);
        if (config != null) {
            Integer has = recordMapper.selectByMemberIdAndConfigId(requestHeaders.getUserid(), config.getId(), now);
            if (has == null) {
                RouseDayMemberRecord record = new RouseDayMemberRecord();
                record.setHasDeleted(0);
                record.setCreateTime(LocalDateTime.now());
                record.setModifyTime(LocalDateTime.now());
                record.setMemberId(requestHeaders.getUserid());
                record.setRouseConfigId(config.getId());
                record.setCreateDate(LocalDate.now());
                record.setImei(requestHeaders.getImei());
                record.setIpAddress(requestHeaders.getIpAddr());
                record.setAppStore(requestHeaders.getAppStore());
                record.setVersion(requestHeaders.getVersion());
                record.setMacAddr(requestHeaders.getMacAddr());
                record.setOsv(requestHeaders.getOsv());
                record.setMemo(config.getMemo());
                recordMapper.insertSelective(record);
                this.addCountByMemberId(requestHeaders, config.getWorth());
            }
        }
    }

    /**
     * 用户增加进度
     *
     * @param requestHeaders
     * @param count
     */
    public void addCountByMemberId(RequestHeaders requestHeaders, Integer count) {
        LocalDate now = LocalDate.now();
        long memberCount = redisClient.hincrby(this.getCountKey(), requestHeaders.getUserid(), count.longValue());
        List<RouseCountConfig> list = this.selectCountConfigList();
        for (RouseCountConfig s : list) {
            if (memberCount >= s.getCount()) {
                Integer check = countRecordMapper.selectByMemberIdAndConfigId(requestHeaders.getUserid(), s.getId(), now);
                if (check == null) {
                    RouseCountMemberRecord record = new RouseCountMemberRecord();
                    record.setHasDeleted(0);
                    record.setCreateTime(LocalDateTime.now());
                    record.setModifyTime(LocalDateTime.now());
                    record.setMemberId(requestHeaders.getUserid());
                    record.setRouseConfigId(s.getId());
                    record.setStatus(0);
                    record.setCreateDate(LocalDate.now());
                    record.setRewardType(s.getRewardType());
                    record.setRewardWorth(this.getByType(s));
                    record.setImei(requestHeaders.getImei());
                    record.setIpAddress(requestHeaders.getIpAddr());
                    record.setAppStore(requestHeaders.getAppStore());
                    record.setVersion(requestHeaders.getVersion());
                    record.setMacAddr(requestHeaders.getMacAddr());
                    record.setOsv(requestHeaders.getOsv());
                    record.setMemo(s.getMemo());
                    String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
                    record.setTradeNo("FASTPAY"+dateStr);
                    this.countRecordMapper.insertSelective(record);

                }
            }
        }
    }

    /**
     * 根据类型返回对应的奖励值
     * @param s
     * @return
     */
    private Integer getByType(RouseCountConfig s) {
        if (s.getRewardType().equals(RewardTypeUscan.Cash.getIndex())) {
            return s.getRewardMoney();
        } else if (s.getRewardType().equals(RewardTypeUscan.Point.getIndex())) {
            return s.getRewardPoint();
        } else {
            return s.getRewardRebate();
        }
    }

    public String getCountKey() {
        return COUNT_KEY + LocalDate.now().format(DateTimeFormatter.ISO_DATE);
    }
}
